import WxValidate from '../../../utils/WxValidate.js';
import http from '../../../utils/http.js';
import ocr from '../../../utils/ocr.js';
const {
  $Message
} = require('../../../component/iview/base/index');

const filesImageArray = [{
    text: '车辆左前方斜视45度照片',
    field: 'leftFront',
    "required": true,

  }, {
    text: '车辆右后方斜视45度照片',
    field: 'rightBack',
    "required": true,
  },
  {
    text: '车辆识别代码照片',
    field: 'vinPhoto',
    "required": false,
  }, {
    text: '三角警示牌',
    field: 'warningTriangle',
    "required": true,

  }, {
    text: '安全带',
    field: 'frontRow',
    "required": true,
  }, {
    text: '发动机(电动机)型号和出厂编号',
    field: 'engine',
    "required": false,
  },
  {
    text: '机动车标准照',
    field: 'standard',
    // "required": true,
  },
  {
    text: '车架号拓印膜',
    field: 'vinRubbing',
    "required": false,
  },
  {
    text: '其他1',
    field: 'checkMore_1'
  },
  {
    text: '其他2',
    field: 'checkMore_2'
  }
];
const filesStandardArray = [{
    text: '机动车标准照',
    field: 'standard',
    "required": true,
  },
  {
    text: '车辆识别代码照片',
    field: 'vinPhoto',
    "required": false,
  },
  {
    text: '发动机(电动机)型号和出厂编号',
    field: 'engine',
    "required": false,
  },
  {
    text: '车架号拓印膜',
    field: 'vinRubbing',
    "required": false,
  },
];
Page({


  /**
   * 页面的初始数据
   */
  data: {
    funcCode: '',
    currentStep: 1,
    // 省份简写
    provinces: [
      ['京', '沪', '粤', '津', '冀', '晋', '蒙', '辽', '吉', '黑'],
      ['苏', '浙', '皖', '闽', '赣', '鲁', '豫', '鄂', '湘'],
      ['桂', '琼', '渝', '川', '贵', '云', '藏'],
      ['陕', '甘', '青', '宁', '新'],
    ],
    // 车牌输入
    numbers: [
      ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
      ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K"],
      ["L", "M", "N", "P", "Q", "R", "S", "T", "U", "V"],
      ["W", "X", "Y", "Z", "港", "澳", "学"]
    ],
    plateNoArray: ['闽', 'D'], //输入车牌，每个字符占一位
    carnoFlag: false,
    plateNo: '',
    showNewPower: false,
    KeyboardState: true,
    files: {},
    filesFlag: {},
    filesField: [{
        text: '机动车标准照',
        field: 'standard',
        // "required": true,
      }, {
        text: '车辆左前方斜视45度照片',
        field: 'leftFront',
        "required": true,

      }, {
        text: '车辆右后方斜视45度照片',
        field: 'rightBack',
        "required": true,
      },
      {
        text: '车辆识别代码照片',
        field: 'vinPhoto',
        "required": true,
      }, {
        text: '三角警示牌',
        field: 'warningTriangle',
        "required": true,

      }, {
        text: '安全带',
        field: 'frontRow',
        "required": true,
      }, {
        text: '发动机(电动机)型号和出厂编号',
        field: 'engine',
        "required": true,
      },
      {
        text: '车架号拓印膜',
        field: 'vinRubbing',
        "required": true,
      },
      {
        text: '其他1',
        field: 'checkMore_1'
      },
      {
        text: '其他2',
        field: 'checkMore_2'
      }
    ],
    pics: [],
    formData: {
      "vehicle.isImported": 0,
      "destination": '福建省厦门市',
      "seller.creditType": "P1",
      "buyer.creditType": "P1",
    },
    filepath: [],
    flagEdit: false,
    plateId: '',
    deleteBtnFlag: false,
    flagTips: '',
    tipState: true,
    userIntroFlag: false,
    imagesData:{}
  },
  // 选中点击设置
  bindChoose(e) {
    // let index = 6;
    // if (this.data.showNewPower) {
    //   index = 7;
    // } else {
    //   index = 6;
    // }
    if (!this.data.plateNoArray[6] || this.data.showNewPower) {
      var arr = [];
      arr[0] = e.target.dataset.val;
      this.data.plateNoArray = this.data.plateNoArray.concat(arr)
      this.setData({
        plateNoArray: this.data.plateNoArray
      })
    }
    if (this.data.plateNoArray.length == 8) {
      this.setData({
        KeyboardState: false,
      })
    }
    if (this.data.plateNoArray.length == 9) {
      if (this.data.plateNoArray.length != 0) {
        this.data.plateNoArray.splice(this.data.plateNoArray.length - 1, 1);
        this.setData({
          plateNoArray: this.data.plateNoArray,
        })
      }
    }


  },
  bindDelChoose() {
    if (this.data.plateNoArray.length != 0) {
      this.data.plateNoArray.splice(this.data.plateNoArray.length - 1, 1);
      this.setData({
        plateNoArray: this.data.plateNoArray,
        carnoFlag: false,
        files: {}, // 回退车牌号图片清空
        tipState: true,
        userIntroFlag: false,
      })
    }
  },
  showPowerBtn() {
    this.setData({
      showNewPower: true,
      KeyboardState: true,
      plateNoArray: this.data.plateNoArray,
      carnoFlag: false,
    })
  },
  closeKeyboard() {
    this.setData({
      KeyboardState: false,

    })
  },
  openKeyboard() {
    this.setData({
      KeyboardState: true
    })
  },
  tips: function(state) {
    if (state == 0) {
      this.setData({
        flagTips: '已上传,可进行修改'
      })
    } else if (state == 1) {
      this.setData({
        deleteBtnFlag: true,
        flagTips: '已完成，不可修改'
      })
    } else if (state == 2 || state == null || state == '') {
      this.setData({
        flagTips: '未上传，请上传图片'
      })
    } else if (state == 3) {
      this.setData({
        flagTips: '无权限'
      })
    }
  },
  // 提交车牌号码
  submitNumber(e) {
    let plateNo = this.data.plateNoArray.join('');
    let type = e.currentTarget.dataset.type;
    if (type == 2) {
      if (!this.isCarPlate(plateNo)) {
        wx.showToast({
          title: '请输入正确的车牌号',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      wx.showLoading({
        title: '数据加载中...',
        mask: true
      })
      http.request({
        url: '/checkImage/wx/findWxCheckImage',
        data: {
          plateNo: plateNo
        },
        success: (res) => {
          wx.hideLoading({});
          let filesFlag = {};
          let image = {};
          if (res != null) {
            let array = this.data.filesField;
            for (let i = 0; i < array.length; i++) {
              let field = array[i].field;
              if (res[field] != null && res[field] != '') {
                let src = http.apiUrl + http.imgUrl + "?imagePath=" + res[field] +
                  "&" + wx.getStorageSync("sessionid")
                image[field] = encodeURI(src);
                filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              }
            }
          }
          console.log(image)
          this.tips(res.state);
          this.setData({
            files: image,
            plateId: res.id,
            tipState: false,
            imagesData: res
          })
        },
      });
      this.setData({
        plateNo: plateNo,
        currentStep: this.data.currentStep + 1,
        carnoFlag: true,
        KeyboardState: false,
        userIntroFlag: true,
      });
    } else {
      if (!this.isCarPlate(plateNo)) {
        wx.showToast({
          title: '请输入正确的车牌号',
          icon: 'none',
          duration: 2000
        })
        return false;
      }
      wx.showLoading({
        title: '数据加载中...',
        mask: true
      })
      http.request({
        url: '/checkImage/wx/findWxStandardImage',
        data: {
          plateNo: plateNo
        },
        success: (res) => {
          wx.hideLoading({});
          let filesFlag = {};
          let image = {};
          if (res != null) {
            let array = this.data.filesField;
            for (let i = 0; i < array.length; i++) {
              let field = array[i].field;
              if (res[field] != null && res[field] != '') {
                let src = http.apiUrl + http.imgUrl + "?imagePath=" + res[field] +
                  "&" + wx.getStorageSync("sessionid")
                image[field] = encodeURI(src);
                filesFlag[field] = 0; // 0表示这是之前上传过的，1表示是新上传的
              }
            }
          }
          this.tips(res.state);
          this.setData({
            files: image,
            plateId: res.id,
            tipState: false,
            imagesData:res
          })
        },
      });
      this.setData({
        plateNo: plateNo,
        currentStep: this.data.currentStep + 1,
        carnoFlag: true,
        KeyboardState: false,
        userIntroFlag: true,
      });
    }
    // if (this.data.plateNoArray[6]) {
    //   // 跳转到tabbar页面
    // }


  },
  cancelData: function() {
    let that = this;
    wx.showModal({
      title: '取消查询拍照',
      content: '确定取消查验拍照吗？',
      success(res) {
        if (res.confirm) {
          that.setData({
            currentStep: 0,
            plateNoArray: ['闽', 'D'],
            carnoFlag: false,
            userIntroFlag: false,
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /* 判断车牌号 */
  isCarPlate(value) {
    return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(value);
  },
  /***
   * 上传图片
   */
  upLoadImage: function(images) {
    var that = this;
    let data = JSON.parse(JSON.stringify(this.data.files[0]));
    for (let key in data) {
      if (data[key] == null) {
        delete data[key];
      }
    }
    delete data["image"];
    if (images != null) {
      for (let key in images) {
        data[key] = images[key];
      }
    }
    data.plateNo = this.data.plateNo;
    delete data.insertTime;
    delete data.orgCode;
    delete data.state;
    if (this.data.flagEdit == true) {
      http.request({
        url: '/checkImage/wx/saveWxCheckImage',
        data: data,
        success: (res) => {
          wx.hideLoading({});
          $Message({
            content: "提交成功",
            type: 'success'
          });

        },
        error: (res) => {
          wx.hideLoading({});
          $Message({
            content: "提交失败," + res.replace('ServiceException:', ''),
            type: 'error'
          });
        }
      });
    } else {
      return;
    }
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.img, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.img] // 需要预览的图片http链接列表
    })
  },
  deleteImage: function(e) {
    this.setData({
      filepath: null
    });
  },

  //上传图片
  chooseImage: function(e) {
    let that = this;
    let chooseImageType = [];
    if (e.target.dataset.field === 'vinPhoto' || e.target.dataset.field === 'engine'){
      chooseImageType = ['original', 'compressed'];
    }else{
      chooseImageType = ['compressed'];
    }
    wx.chooseImage({
      sizeType: chooseImageType,
      //sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      //sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      count: 1,
      success: function(res) {
        let files = that.data.files;
        files[e.currentTarget.dataset.field] = res.tempFilePaths[0];
        var filesFlag = that.data.filesFlag;
        filesFlag[e.currentTarget.dataset.field] = true; // 0表示这是之前上传过的，1表示是新上传的
        that.setData({
          files: files,
          filesFlag: filesFlag,
          flagEdit: true
        });
      }
    })
  },
  // 删除多图
  deleteImageList: function(e) {
    let that = this;
    var files = that.data.files;
    let msg = e.currentTarget.dataset.text;
    // console.log(msg);
    wx.showModal({
      title: '确认删除?',
      content: '请确认是否删除【' + msg + '】照片',
      success(res) {
        if (res.confirm) {
          files[e.currentTarget.dataset.field] = null; 
          let filesFlag = that.data.filesFlag;
          filesFlag[e.currentTarget.dataset.field] = true;
          //filesFlag[e.currentTarget.dataset.field] = null; // 0表示这是之前上传过的，1表示是新上传的
          that.setData({
            files: files,
            flagEdit: true,
            filesFlag: filesFlag
          });
          console.log(files)
          console.log(filesFlag)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }

      }
    })

    // let type = e.currentTarget.dataset.type;

  },
  imageToBase64: function(index, images) {
    let field = this.data.filesField[index]["field"];
    index++;
    if (this.data.filesFlag[field] == true) {
      //说明这张图片是新增
      let file = this.data.files[field];
      wx.getFileSystemManager().readFile({
        filePath: file, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          images[field] = "data:image/jpeg;base64," + res.data;
        },
        complete: () => {
          if (index < this.data.filesField.length) {
            this.imageToBase64(index, images);
          } else {
            this.saveData(images);
          }
        }
      })
    } else if (this.data.filesFlag[field] == false) {
      //说明这张图片是修改时回显的
      images[field] = this.data.formData["image"][field] //直接上传原先的地址
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    } else {
      if (index < this.data.filesField.length) {
        this.imageToBase64(index, images);
      } else {
        this.saveData(images);
      }
    }
  },


  //提交保存数据
  sumbitData: function() {
    let filesField = this.data.filesField;
    let files = this.data.files;
    let flagEdit= this.data.flagEdit;
    if (flagEdit === false){
      $Message({
        content: "暂无修改",
        type: 'error'
      });
    }
    for (let i = 0; i < filesField.length; i++) {
      if (filesField[i]["required"] === true) {
        if (files[filesField[i]["field"]] == null || files[filesField[i]["field"]] == "") {
          $Message({
            content: filesField[i]["text"] + "必须上传",
            type: 'error'
          });
          return;
        }
      }
    }
    this.imageToBase64(0, {});
    this.setData({
      show: true,
    })
  },

  saveData: function(images) {
    var that = this;
    let data = JSON.parse(JSON.stringify(this.data.files));
    for (let key in data) {
      if (data[key] == null) {
        delete data[key];
      }
    }
    delete data["image"];
    if (images != null) {
      for (let key in images) {
        data[key] = images[key];
      }
    }
    data.plateNo = this.data.plateNo;
    data.id = this.data.plateId
    delete data.insertTime;
    delete data.orgCode;
    delete data.state;
    let funcCode = this.data.funcCode;
    let requestUrl = '';
    let filesFlag = this.data.filesFlag;
    let imagesData= this.data.imagesData;
    if (funcCode == 'DB'){
      for (let i = 0; i < filesStandardArray.length; i++) {
        if (filesFlag[filesStandardArray[i].field] === true) {
        } else {
          data[filesStandardArray[i].field] = imagesData[filesStandardArray[i].field];
        }
      }
    } else if (funcCode == "CY"){
      for (let i = 0; i < filesImageArray.length; i++) {
        if (filesFlag[filesImageArray[i].field] === true) {
        } else {
          data[filesImageArray[i].field] = imagesData[filesImageArray[i].field];
        }
      }
    }
   
  

    if (this.data.flagEdit == true) {
      if (funcCode == 'DB') {
        requestUrl = '/checkImage/wx/saveWxStandardImage'
      } else if (funcCode == "CY") {
        requestUrl = '/checkImage/wx/saveWxCheckImage'
      }
      wx.showLoading({
        title: '正在提交中...',
        mask: true
      })

      http.request({
        url: requestUrl,
        data: data,
        success: (res) => {
          wx.hideLoading({});
          wx.showModal({
            title: '提交成功',
            content: data.plateNo + '查验照片提交成功！',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                that.setData({
                  plateNoArray: ['闽', 'D'],
                  carnoFlag: false,
                  tipState: true,
                  userIntroFlag: false,
                  flagEdit:false,
                  filesFlag: {}
                })
              }
            }
          })


        },
        error: (res) => {
          wx.hideLoading({});
          $Message({
            content: "提交失败," + res.replace('ServiceException:', ''),
            type: 'error'
          });
        }
      });

    } else {
      return;
    }
  },

  submitStandard: function(images) {
    var that = this;
    let data = JSON.parse(JSON.stringify(this.data.files['standard']));
    for (let key in data) {
      if (data[key] == null) {
        delete data[key];
      }
    }
    delete data["image"];
    if (images != null) {
      for (let key in images) {
        data[key] = images[key];
      }
    }
    data.plateNo = this.data.plateNo;
    delete data.insertTime;
    delete data.orgCode;
    delete data.state;
    if (this.data.flagEdit == true) {
      http.request({
        url: '/checkImage/wx/saveWxCheckImage',
        data: data,
        success: (res) => {
          wx.hideLoading({});
          $Message({
            content: "提交成功",
            type: 'success'
          });

        },
        error: (res) => {
          wx.hideLoading({});
          $Message({
            content: "提交失败," + res.replace('ServiceException:', ''),
            type: 'error'
          });
        }
      });
    } else {
      return;
    }
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.type == 1) {
      this.setData({
        funcCode: 'DB',
        filesField: filesStandardArray
      })
    } else if (options.type == 2) {
      this.setData({
        funcCode: 'CY',
        filesField: filesImageArray
      })
    }
    // this.setData({
    //   funcCode: options.funcCode
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})